package com.sskj.bibi.ui.fragment;


import android.support.design.widget.BottomSheetDialog;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.sskj.bibi.R;
import com.sskj.bibi.R2;
import com.sskj.bibi.presenter.PankouUpDownFragmentPresenter;
import com.sskj.common.adapter.ItemClickSupport;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.BibiCoinType;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.WSFiveBean;
import com.sskj.lib.bean.enums.ColorEnum;
import com.sskj.lib.box.LiveDataBus;
import com.sskj.lib.util.BottomSheetUtil;
import com.sskj.lib.util.CoinUtil;
import com.sskj.lib.util.NumberUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;

@Route(path = RConfig.BIBI_FRAGMENT_PANKOU)
public class PankouUpDownFragment extends BaseFragment<PankouUpDownFragmentPresenter> {
    private static final int MAX_SIZE = 8;
    @BindView(R2.id.tvPrice)
    TextView tvPrice;
    @BindView(R2.id.tvRMBPrice)
    TextView tvRMBPrice;

    @BindView(R2.id.buyRecyclerView)
    RecyclerView buyRecyclerView;
    @BindView(R2.id.sellRecyclerView)
    RecyclerView sellRecyclerView;
    @BindView(R2.id.loading_layout)
    FrameLayout loadingFrameLayout;
    @BindView(R2.id.llGrade)
    LinearLayout llGrade;
    @BindView(R2.id.tvNumDot)
    TextView tvNumDot;
    @Autowired
    String code;

    private SlimAdapter buySlimAdapter;
    private SlimAdapter sellSlimAdapter;
    private BottomSheetDialog bottomSheet;
    private int grade;
    private int gradeMax;
    private int mLength = 6;


    @Override
    protected int getLayoutId() {
        return R.layout.bibi_fragment_pankou_up_down;
    }

    @Override
    public PankouUpDownFragmentPresenter getPresenter() {
        return new PankouUpDownFragmentPresenter();
    }

    @Override
    public void initView() {
        ARouter.getInstance().inject(this);
        RxBus.getDefault().register(this);
        buyRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        sellRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        buySlimAdapter = SlimAdapter.create().register(R.layout.bibi_recy_item_pankou_up_down, new SlimInjector<WSFiveBean.FiveBean>() {
            @Override
            public void onInject(WSFiveBean.FiveBean data, IViewInjector injector, List payloads) {

                Log.d("yds", CoinUtil.keepCoinNumMax(data.getCode(), data.getTotalSize())+"------------"+data.getCode()+"-----------"+data.getTotalSize());
                injector
                        .text(R.id.tvOrderNum, buySlimAdapter.getData().indexOf(data) + 1 + "")
                        .text(R.id.tvPrice, TextUtils.isEmpty(data.getPrice()) ? "---" : gradePrice(data.getPrice()))
                        .text(R.id.tvNum, TextUtils.isEmpty(data.getTotalSize()) ? "---" : CoinUtil.keepCoinNum(data.getCode(), data.getTotalSize()))
                        .textColor(R.id.tvPrice, ContextCompat.getColor(App.INSTANCE, R.color.bibiGreenText))
                        .with(R.id.bibiProgressbar, view -> {
                            ProgressBar progressBar = (ProgressBar) view;
                            progressBar.setProgressDrawable(ContextCompat.getDrawable(App.INSTANCE, R.drawable.bibi_progress_green));
                            progressBar.setProgress(data.getPercent());
                        })
                ;
            }
        });
        buySlimAdapter.attachTo(buyRecyclerView).updateData(new ArrayList());
        sellSlimAdapter = SlimAdapter.create().register(R.layout.bibi_recy_item_pankou_up_down, new SlimInjector<WSFiveBean.FiveBean>() {
            @Override
            public void onInject(WSFiveBean.FiveBean data, IViewInjector injector, List payloads) {
                injector
                        .text(R.id.tvOrderNum, "" + (sellSlimAdapter.getItemCount() - sellSlimAdapter.getData().indexOf(data)))
                        .text(R.id.tvPrice, TextUtils.isEmpty(data.getPrice()) ? "---" : gradePrice(data.getPrice()))
                        .text(R.id.tvNum, TextUtils.isEmpty(data.getTotalSize()) ? "---" : CoinUtil.keepCoinNum(data.getCode(), data.getTotalSize()))
                        .textColor(R.id.tvPrice, ContextCompat.getColor(App.INSTANCE, R.color.bibiRedText))
                        .with(R.id.bibiProgressbar, view -> {
                            ProgressBar progressBar = (ProgressBar) view;
                            progressBar.setProgressDrawable(ContextCompat.getDrawable(App.INSTANCE, R.drawable.bibi_progress_red));
                            progressBar.setProgress(data.getPercent());
                        })
                ;
            }
        });
        sellSlimAdapter.attachTo(sellRecyclerView).updateData(new ArrayList());

        ItemClickSupport.addTo(buyRecyclerView)
                .setOnItemClickListener((recyclerView, i, view) -> {
                    if (i < 0) {
                        return;
                    }
                    WSFiveBean.FiveBean dataItem = (WSFiveBean.FiveBean) buySlimAdapter.getDataItem(i);
                    LiveDataBus.get().with(RxBusCode.CHANGE_PRICE, String.class)
                            .postValue(dataItem.getPrice());
                });
        ItemClickSupport.addTo(sellRecyclerView)
                .setOnItemClickListener((recyclerView, i, view) -> {
                    if (i < 0) {
                        return;
                    }
                    WSFiveBean.FiveBean dataItem = (WSFiveBean.FiveBean) sellSlimAdapter.getDataItem(i);
                    LiveDataBus.get().with(RxBusCode.CHANGE_PRICE, String.class)
                            .postValue(dataItem.getPrice());


                });

    }

    public String gradePrice(String price) {
        if (price == null) {
            return price;
        }

        try {
            String newPrice = NumberUtil.keep(price, grade);
            return NumberUtil.keep(newPrice + "", gradeMax);
        } catch (Exception e) {
            return price;
        }

    }

    @Override
    public void initData() {
        updateCoin(new BibiCoinType(code));
        LiveDataBus.get().with(RxBusCode.PUSH_COIN_BEAN,CoinBean.class)
                .observe(this,this::refreshCoin);
    }

    /**
     * 设置买五卖五UI --
     */
    public void resetFiveUI() {
        loadingFrameLayout.setVisibility(View.VISIBLE);
        WSFiveBean wsFiveBean = new WSFiveBean();
        wsFiveBean.setCode(code);
        ArrayList<WSFiveBean.FiveBean> asks = new ArrayList<>();
        ArrayList<WSFiveBean.FiveBean> bids = new ArrayList<>();
        for (int i = 0; i < MAX_SIZE; i++) {
            asks.add(new WSFiveBean.FiveBean(null, null));
            bids.add(new WSFiveBean.FiveBean(null, null));
        }
        wsFiveBean.setAsks(asks);
        wsFiveBean.setBids(bids);
        tvPrice.setText("--");
        tvRMBPrice.setText("--");
        updateFive(wsFiveBean);
    }

    /**
     * 刷新页面
     */
    @Subscribe(code = RxBusCode.BIBI_FRESH, threadMode = ThreadMode.MAIN)
    public void refresh() {
        mPresenter.getProduct(code);
        mPresenter.getPankou(code);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateFive(WSFiveBean wsFiveBean) {
        if (wsFiveBean != null && wsFiveBean.getCode() != null) {
            if (wsFiveBean.getCode().equalsIgnoreCase(code)) {
                if (loadingFrameLayout != null) {
                    loadingFrameLayout.setVisibility(View.GONE);
                }
                Collections.reverse(wsFiveBean.getAsks());
                int bidSize = wsFiveBean.getBids().size();
                for (int i = 0; i < MAX_SIZE - bidSize; i++) {
                    wsFiveBean.getBids().add(new WSFiveBean.FiveBean(null, null));
                }
                int askSize = wsFiveBean.getAsks().size();
                for (int i = 0; i < MAX_SIZE - askSize; i++) {
                    wsFiveBean.getAsks().add(0, new WSFiveBean.FiveBean(null, null));
                }

                List<WSFiveBean.FiveBean> sellFiveBean = wsFiveBean.getAsks().subList(wsFiveBean.getAsks().size() - MAX_SIZE, wsFiveBean.getAsks().size());
                List<WSFiveBean.FiveBean> buyFiveBean = wsFiveBean.getBids().subList(0, MAX_SIZE);
                wsFiveBean.setAsks(sellFiveBean);
                wsFiveBean.setBids(buyFiveBean);
                calculatePercentAll(wsFiveBean);
                sellSlimAdapter.updateData(wsFiveBean.getAsks());
                buySlimAdapter.updateData(wsFiveBean.getBids());
            }
        }
    }

    private void calculatePercentAll(WSFiveBean wsFiveBean) {
        Double full = 0d;
        for (WSFiveBean.FiveBean bid : wsFiveBean.getBids()) {
            Double aDouble = Double.valueOf(bid.getDoubleTotalSize());
            if (aDouble > full) {
                full = aDouble;
            }
        }
        for (WSFiveBean.FiveBean ask : wsFiveBean.getAsks()) {
            Double aDouble = Double.valueOf(ask.getDoubleTotalSize());
            if (aDouble > full) {
                full = aDouble;
            }
        }
        for (WSFiveBean.FiveBean bid : wsFiveBean.getBids()) {
            Double aDouble = Double.valueOf(bid.getDoubleTotalSize());
            bid.setPercent((int) (aDouble / full * 100d));
        }

        for (WSFiveBean.FiveBean ask : wsFiveBean.getAsks()) {
            Double aDouble = Double.valueOf(ask.getDoubleTotalSize());
            ask.setPercent((int) (aDouble / full * 100d));
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateCoin(BibiCoinType coinType) {

        code = coinType.getCode();
        gradeMax = CoinUtil.coinGrade(code);
        grade = gradeMax;
        resetFiveUI();
        mPresenter.getProduct(code);
        mPresenter.getPankou(code);
        mPresenter.initSocket(this, code);

    }


    public void refreshCoin(CoinBean coinBean) {
        if (code.equals(coinBean.getCode())) {
            updateTitle(coinBean);
        }
    }

    public void updateTitle(CoinBean stockCoinBean) {
        if (tvPrice == null) {
            return;
        }
        try {
            String codeNew = code.replace("_", "/").toUpperCase();
            String substring = codeNew.substring(codeNew.indexOf("/") + 1);
            if (substring.equals("USDT")) {
                mLength = 6;
            } else {
                mLength = 8;
            }
            tvPrice.setText(NumberUtil.keep(stockCoinBean.getPrice(), mLength));
            tvRMBPrice.setText(String.format("≈%s " + Constans.DANWEI, stockCoinBean.getCnyPrice()));
            tvPrice.setTextColor(ContextCompat.getColor(App.INSTANCE, stockCoinBean.isUp() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()));
        } catch (Exception e) {

        }


    }

    private int getStartGrade(String price) {
        int num = 1;
        while (Double.valueOf(price) * 10 < 1) {
            num++;
            price = Double.valueOf(price) * 10 + "";
        }
        return num;
    }



    /**
     * 接口请求获取
     *
     * @param coinBean
     */
    public void updateCoin(CoinBean coinBean) {
        gradeMax = CoinUtil.coinGrade(code);
        grade = gradeMax;
        updateTitle(coinBean);

        if (Double.valueOf(coinBean.getPrice()) < 1) {

            llGrade.setVisibility(View.GONE);
            return;
        } else {
            llGrade.setVisibility(View.VISIBLE);
        }
        int gradeMin = getStartGrade(coinBean.getPrice());

        ArrayList<String> gradeStr = new ArrayList<>();
        ArrayList<Integer> gradeInt = new ArrayList<>();

        for (int i = gradeMin; i <= gradeMax; i++) {
            gradeStr.add(i + App.INSTANCE.getString(R.string.bibipankouUpDownFragment1));
            gradeInt.add(i);
        }
        tvNumDot.setText(gradeMax + App.INSTANCE.getString(R.string.bibipankouUpDownFragment1));
        bottomSheet = BottomSheetUtil.getBottomSheet(getActivity(), null, (recyclerView, i, view) -> {
            bottomSheet.dismiss();
            tvNumDot.setText(((TextView) view).getText());
            grade = gradeInt.get(i);
            mPresenter.getPankou(code);
        }, gradeStr);
        ClickUtil.click(llGrade, () -> {
            if (bottomSheet == null) {
                return;
            }
            bottomSheet.show();
        });
    }
}
